package bookstudytest.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Lee
 * @Date: 2018/6/20 11:07
 * @Description:
 */
public class BufferServerSocket {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        BufferedReader bufferedReader = null;
        PrintWriter writer = null;
        Socket socket = null;
        String response = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<TRANINFO>\n" +
                " <HEAD>\n" +
                "  HEAD内容\n" +
                " </HEAD>\n" +
                " <MSG>\n" +
                "     报文内容\n" +
                " </MSG>\n" +
                "</TRANINFO>";
        //设定服务端的端口号
        try {
            serverSocket = new ServerSocket(56669);
            //等待请求,此方法会一直阻塞,直到获得请求才往下走
            socket = serverSocket.accept();
            //用于接收客户端发来的请求,得到输入流
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //用于发送返回信息,可以不需要装饰这么多io流使用缓冲流时发送数据要注意调用.flush()方法
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            while (true) {
                String str = bufferedReader.readLine();//接收到的信息
                str = new String(str.getBytes("GBK"), "GBK");
                System.out.println("receive message :" + str);
                if (str.equals("</TRANINFO>")) {
                    break;
                }
            }
            Thread.sleep(1000);
            writer.println(new String(response.getBytes("GBK"),"GBK"));
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                writer.close();
                socket.close();
                serverSocket.close();
            } catch (Exception e) {

            }
        }
    }
}
